package com.leoman.service.impl;

import com.leoman.core.Constant;
import com.leoman.dao.ImageDao;
import com.leoman.entity.Image;
import com.leoman.service.ImageService;
import com.leoman.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ImageServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:58.
 */
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageDao imageDao;

    @Override
    public List<Image> findAll() {
        return imageDao.findAll();
    }

    @Override
    public Page<Image> find(int pageNum, int pageSize) {
        return imageDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Image> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Image getById(int id) {
        return imageDao.findOne(id);
    }

    @Override
    public void deleteById(int id) {
        Image image = imageDao.findOne(id);

        QiNiuUtils.delete(image.getUrl());

        imageDao.delete(id);
    }

    @Override
    public Image create(Image image) {
        return imageDao.save(image);
    }

    @Override
    public Image update(Image image) {
        return imageDao.save(image);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public List<Image> findListBySourceIdAndType(Integer sourceId, Integer type) {
        return imageDao.findListByParams(sourceId, type);
    }
}